package com.yunxi.service.dubboService.impl.otd;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.core.util.DateUtil;
import com.yunxi.core.util.StringUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.otd.OtdInterfaceConfig;
import com.yunxi.model.otd.OtdOrderSo;
import com.yunxi.model.otd.OtdProjectCarOrder;
import com.yunxi.otd.pojo.OtdProjectCarOrderQueryVO;
import com.yunxi.otd.pojo.OtdProjectCarOrderSaveVO;
import com.yunxi.otd.pojo.OtdProjectCarOrderVO;
import com.yunxi.otd.service.OtdProjectCarOrderDubboService;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.VehicleProductViewService;
import com.yunxi.service.localService.otd.OtdInterfaceConfigService;
import com.yunxi.service.localService.otd.OtdOrderSoService;
import com.yunxi.service.localService.otd.OtdProjectCarOrderService;
import com.yunxi.service.localService.otd.VehicleConfigConstraintService;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 项目车订单 服务实现类 state  1 新建 2 确认
 * </p>
 *
 * @author XUQI
 * @since 2019-05-09
 */
public class OtdProjectCarOrderDubboServiceImpl implements OtdProjectCarOrderDubboService {

    private static final Log logger = LogFactory.getLog(OtdProjectCarOrderDubboServiceImpl.class);

    @Autowired
    @Qualifier("otdProjectCarOrderServiceImpl")
    OtdProjectCarOrderService projectCarOrderService;

    @Autowired
    @Qualifier("vehicleProductViewServiceImpl")
    VehicleProductViewService productViewService;

    @Autowired
    @Qualifier("otdInterfaceConfigServiceImpl")
    OtdInterfaceConfigService interfaceConfigService;

    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService code;

//    @Autowired
//    @Qualifier("otdIfProducePlanServiceImpl")
//    OtdIfProducePlanService producePlanService;

    @Autowired
    @Qualifier("otdOrderSoServiceImpl")
    OtdOrderSoService otdOrderSoService;

    @Autowired
    @Qualifier("vehicleConfigConstraintServiceImpl")
    VehicleConfigConstraintService configConstraintService;


    @Override
    public PageInfo findPageByVO(OtdProjectCarOrderQueryVO queryVO, Integer pageNum,
        Integer pageSize) {
        return projectCarOrderService.pageByVo(queryVO, pageNum, pageSize);
    }

    @Override
    public OtdProjectCarOrderVO getById(String id) {
        return projectCarOrderService.findById(id);
    }

    @Override
    public ApiResult saveOrUpdate(OtdProjectCarOrderSaveVO saveVO, LoginInfo loginInfo) {
        OtdProjectCarOrder order = convertBean(saveVO);
        // 校验项目车标记是否重复
        if (projectCarOrderService.checkProjectCarMarkRepeat(order.getProjectCarId(), order.getProjectCarMark())) {
            return ResponseUtil.fail(-1, "重复的项目车标记！");
        }

        // 查询产品Code
        String projectCode = productViewService
            .findProductCodeBySub(saveVO.getCatalogCode(), saveVO.getColorCodeIn(),
                saveVO.getColorCodeOut());
        if (StringUtils.isEmpty(projectCode)) {
            return ResponseUtil.fail(-1, "产品信息填写错误！");
        }
        order.setProductCode(projectCode);
        // id 为空则为新增
        if (StringUtils.isEmpty(saveVO.getProjectCarId())) {
            //新增
//            order.setProjectCarNo(code.createCode("PC", "yyMMdd", 4));
            order.setState("1");//新建
            order.setCreateTime(new Date());
            order.setCreateBy(loginInfo.getUserCode());
            order.setWorks("AP21");
        }
        if (!projectCarOrderService.saveOrUpdate(order)) {
            return ResponseUtil.fail(-1, "刷新后重试！");
        }
        return ResponseUtil.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult importData(List<Map<String, Object>> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return ResponseUtil.fail(-1, "导入数据为空");
        }
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> map = dataList.get(i);
            String projectCarMark = (String) map.get("项目车标记");
            String catalogCode = (String) map.get("配置");
            String colorInCode = (String) map.get("内饰色");
            String colorOutCode = (String) map.get("外饰色");
            String demandDateStr = (String) map.get("需求日期");
            Date demandDate;
            String customPackCode = (String) map.get("选装包");
            ////校验
            if (StringUtils.isEmpty(projectCarMark)) {
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：项目车标记不能为空");
            }
            if (StringUtils.isEmpty(catalogCode)) {
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：配置不能为空");
            }
            if (StringUtils.isEmpty(colorOutCode)) {
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：外饰色不能为空");
            }
            if (StringUtils.isEmpty(colorInCode)) {
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：内饰色不能为空");
            }
            if (StringUtils.isEmpty(demandDateStr)) {
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：需求日期不能为空");
            }
            //需求日期格式化
            demandDate = DateUtil.parse(demandDateStr, "MM/dd/yy");


            // 选装包校验
            if (!StringUtils.isEmpty(customPackCode)) {
                // 是否正确、是否存在互斥
                List<String> packages = Arrays.asList(customPackCode.split("/"));
                boolean check = configConstraintService.checkExcludeCustomPackCode(packages, catalogCode);
                if(!check){
                    throw new RuntimeException("选装包存在互斥：" + customPackCode);
                }
                customPackCode = StringUtil.customPackCodeSort(customPackCode.replace("/", ","));
            }else{
                customPackCode = null;
            }


            // 查询产品Code
            String projectCode = productViewService
                .findProductCodeBySub((String) map.get("配置"), (String) map.get("内饰色"), (String) map.get("外饰色"));
            if (StringUtils.isEmpty(projectCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：产品信息填写错误！");
            }

            // 校验项目车标记是否重复
            if (projectCarOrderService.checkProjectCarMarkRepeat(null, projectCarMark)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseUtil.fail(-1, "第" + (i + 1) + "行：重复的项目车标记！");
            }
            OtdProjectCarOrder order = new OtdProjectCarOrder();
//            order.setProjectCarNo(code.createCode("PC", "yyMMdd", 4));
            order.setProjectCarMark(projectCarMark);
            order.setProductCode(projectCode);
            order.setCustomPackCode(customPackCode);
            order.setDemandDate(demandDate);
            order.setState("1");//新建
            order.setWorks("AP21");
            projectCarOrderService.save(order);
        }
        return ResponseUtil.ok();
    }

    /**
     * 项目车确认  添加周度计划接口数据
     *
     * @param saveVO 项目车订单VO
     * @param loginInfo 登陆信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult confirm(OtdProjectCarOrderSaveVO saveVO, LoginInfo loginInfo) {
        OtdProjectCarOrder order = projectCarOrderService.getById(saveVO.getProjectCarId());

        // 查询接口设置表，需求日期是否已发送
        LambdaQueryWrapper<OtdInterfaceConfig> queryWrapper = new LambdaQueryWrapper<>();
        //PSO项目车订单，状态不为W(未发送)，
        queryWrapper.eq(OtdInterfaceConfig::getType, "PSO")
            .ne(OtdInterfaceConfig::getState, "W")
            .le(OtdInterfaceConfig::getStartDate, order.getDemandDate())
            .ge(OtdInterfaceConfig::getEndDate, order.getDemandDate());
        int count = interfaceConfigService.count(queryWrapper);
        if (count > 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil
                .fail(-1, "日期" + DateUtil.format(order.getDemandDate(), "yyyy-MM-dd") + "项目车订单已下发，无法继续添加！");
        }
        // 添加SO接口订单
        OtdOrderSo soOrder = new OtdOrderSo();
        soOrder.setPlanNo(code.createCode("P", "yyMMdd", 5));
        soOrder.setProductCode(order.getProductCode());
        soOrder.setCustomPackCode(order.getCustomPackCode());
        soOrder.setCarName(otdOrderSoService.generateCarName(order.getProductCode(), order.getCustomPackCode()));
        soOrder.setDemandDate(order.getDemandDate());//预计生产日期
        soOrder.setInterfaceType("I");//接口类型：新增
        soOrder.setCarLimitState(0);
        soOrder.setOrderType(DictConstant.OTD_ORDER_TYPE_PRVE);//订单类型:项目用车
        soOrder.setProjectCarMark(order.getProjectCarMark());// 项目车标记
        soOrder.setWorks(order.getWorks());// 工厂
//        soOrder.setCusOrderNo("AS99");
        soOrder.setSapState("N");//待发送
//        soOrder.setPriority("2");//优先级
        otdOrderSoService.save(soOrder);

        order.setVersion(saveVO.getVersion());
        order.setState("2");
        order.setProjectCarNo(soOrder.getPlanNo());// 计划号
        if (!projectCarOrderService.updateById(order)) {
            return ResponseUtil.fail(-1, "刷新后重试！");
        }
        return ResponseUtil.ok();

/*
        // 查询生产日历
        OtdWeekCalendar calendar = calendarService.findCalendarByDate(order.getDemandDate());
        if (calendar == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.fail(-1, "生产日历中未包含" + DateUtil.format(order.getDemandDate(), "yyyy-MM-dd") + "!");
        }
        // 添加周度计划接口数据
        OtdIfProducePlan ifPlan = new OtdIfProducePlan();
        ifPlan.setPlanNo(code.createCode("WPLAN", 5));
//        ifPlan.setWeekPlanCode(weekPlan.getWeekPlanCode());
        ifPlan.setOrderYear(calendar.getYear());
        ifPlan.setOrderMonth(calendar.getMonth());
        ifPlan.setOrderWeek(calendar.getWeek());
        ifPlan.setProductCode(order.getProductCode());
        ifPlan.setExpectedDemandDate(order.getDemandDate());//预计生产日期
        ifPlan.setInterfaceType("I");//接口类型：新增
        ifPlan.setVehicleCode(productViewVO.getSeriesCode());//车系
        ifPlan.setOrderType("PRVE");//订单类型:项目用车
        ifPlan.setCarModel(productViewVO.getCatalogCode());//变量车型（15位物料码）
        ifPlan.setCarName(generateCarName(productViewVO, order.getCustomPackCode()));// 整车描述
        ifPlan.setCustomPackCode(order.getCustomPackCode());
        ifPlan.setZzpack(productViewVO.getBatteryPackCode());//电池包
        ifPlan.setCarLimitState("0");//整车下线限制类型
        ifPlan.setCarLimitReason("");
        ifPlan.setProjectCarNo(order.getProjectCarNo());// 项目车单号
        ifPlan.setPriority("2");//优先级
        ifPlan.setWorks("AP21");// 工厂
        ifPlan.setCreateBy(loginInfo.getRealName());
        ifPlan.setUpdateBy(loginInfo.getRealName());
        ifPlan.setSapState("N");//待发送
        producePlanService.save(ifPlan);
*/

    }


    /**
     * 根据ID删除项目车订单
     *
     * @param ids ids
     * @return ApiResult
     */
    @Override
    public ApiResult remover(List<String> ids) {
        //校验状态
        LambdaQueryWrapper<OtdProjectCarOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OtdProjectCarOrder::getProjectCarId, ids).eq(OtdProjectCarOrder::getState, "1");
        int count = projectCarOrderService.count(queryWrapper);
        if (count != ids.size()) {
            logger.debug("ids:" + ids.size() + "count" + count);
            return ResponseUtil.fail(-1, "存在不允许删除的订单状态，请稍后重试！");
        }
        projectCarOrderService.removeByIds(ids);
        return ResponseUtil.ok();
    }

    /**
     * VO to Bean
     *
     * @param orderVO VO
     * @return Bean
     */
    private OtdProjectCarOrder convertBean(OtdProjectCarOrderSaveVO orderVO) {
        OtdProjectCarOrder order = new OtdProjectCarOrder();
        BeanUtils.copyProperties(orderVO, order);
        return order;
    }

    /**
     * 不分页查询
     * @param queryVO 查询条件VO
     * @return ApiResult
     */
    @Override
    public ApiResult findListByVO(OtdProjectCarOrderQueryVO queryVO) {
        return ResponseUtil.ok(projectCarOrderService.listByVo(queryVO));
    }
}
